package net.sashag.nadlandroid;

import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.util.Log;

import com.parse.ParseException;
import com.parse.ParsePush;

public class NadlandroidPushNewApartment {

	private static final String NEW_APARTMENT_ACTION = "net.sashag.nadlandroid.NEW_APARTMENT_ACTION";
	
	private String apartmentId;
	private String regionName;
	private Date time;
	private List<String> channels;

	public NadlandroidPushNewApartment(String apartmentId, List<String> channels) {
		this.apartmentId = apartmentId;
		this.channels = channels;
		this.time = new Date();
	}
	
	private NadlandroidPushNewApartment(String apartmentId, String regionName, Date time) {
		this.apartmentId = apartmentId;
		this.regionName = regionName;
		this.time = time;
	}
	
	public String getApartmentId() {
		return apartmentId;
	}
	public String getRegionName() {
		return regionName;
	}
	public Date getTime() {
		return time;
	}
	
	public static NadlandroidPushNewApartment fromIntent(Intent intent) throws JSONException {
		String channel = intent.getStringExtra("com.parse.Channel");
		JSONObject data = new JSONObject(intent.getStringExtra("com.parse.Data"));
		String apartmentId = data.getString("apartment");
		Date time = new Date(data.getLong("time"));
		return new NadlandroidPushNewApartment(apartmentId, channel, time);
	}

	public void send() {
		try {
			JSONObject data = new JSONObject();
			data.put("action", NEW_APARTMENT_ACTION);
			data.put("time", time.getTime());
			data.put("apartment", apartmentId);
			ParsePush push = new ParsePush();
			push.setChannels(channels);
			push.setData(data);
			push.send();
		} catch (JSONException e) {
			Log.w("Apartment", "JSON exception constructing push message: " + e.getMessage());
		} catch (ParseException e) {
			Log.w("Apartment", "Error sending push: " + e.getMessage());
		}
	}
}
